# coding:utf-8


import requests, re, time
from urllib3.exceptions import InsecureRequestWarning
from bs4 import BeautifulSoup
from Common.Config import Config

class LoginCookie():
    def __init__(self):
        env = Config().get_conf('comm', 'env')
        self.username = Config().get_conf(env, 'ob_username')
        self.password = Config().get_conf(env, 'ob_password')

    def getSysCookie(self):

        url = 'http://47.96.53.33:8080/casservice/login?service=http%3A%2F%2Fuat.crm.aihuishou.com%2Fhome%2Fcaslogin%3Fredirect%3D%252F'

        # 禁用安全请求警告
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        login_session = requests.session()  # 创建session对象保存所有登录会话请求
        login_session.keep_alive = False

        # Get请求获取登陆使用Lt和execution数据
        res = login_session.get(url, verify=False)
        cook = res.cookies
        # print(cook['SESSION'])
        html = res.content
        soup = BeautifulSoup(html, 'lxml')
        it = soup.select('input[name="lt"]')[0].get('value')
        execution = soup.select('input[name="execution"]')[0].get('value')
        _eventId = soup.select('input[name="_eventId"]')[0].get('value')
        login_data = {
            'username': self.username,
            'password': self.password,
            'lt': it,
            'execution': execution,
            '_eventId': _eventId
        }

        header = {
            'Proxy-Connection': 'keep-alive',
            'Content-Length': '148',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cache-Control': 'max-age=0',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Origin': 'http://47.96.53.33:8080',
            'Host': '47.96.53.33:8080',
            'Referer': 'http://47.96.53.33:8080/casservice/login?service=http%3A%2F%2Fuat.crm.aihuishou.com%2Fhome%2Fcaslogin%3Fredirect%3D%252F',
            'Cookie': 'SESSION=' + cook[
                'SESSION'] + ';lang=zh_CN; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN'
        }

        # Post请求获取SSO分配的Ticket
        res = login_session.post(url, headers=header, data=login_data, cookies=cook, allow_redirects=False,
                                 verify=False)

        # print(res.text, '\n', res.headers)
        location = res.headers['Location']

        # 通过Ticket发送Get请求获取cookies
        res = login_session.get(location, allow_redirects=False, verify=False)
        cookie = res.cookies
        # print(cookie)
        return cookie


if __name__ == '__main__':
    L = LoginCookie()
    L.getSysCookie()
